#include "../server.hpp"
#include <iostream>
#include <chrono>
#include <thread>
#include <csignal>
#include <unistd.h>
#include <cassert>

void logMessage(const std::string& message) {
    std::cout << message << std::endl;
}

void signalHandler(int signum) {
    logMessage("Interrupt signal (" + std::to_string(signum) + ") received.");
    // Cleanup and close up stuff here
    exit(signum);
}

int main() {
    signal(SIGCHLD, SIG_IGN); // 忽略子进程退出信号

    for (int i = 0; i < 10; i++) {
        pid_t pid = fork();
        if (pid < 0) {
            logMessage("FORK ERROR");
            return -1;
        } else if (pid == 0) {
            try {
                Socket cli_sock;
                if (!cli_sock.CreateClient(8085, "127.0.0.1")) {
                    throw std::runtime_error("Failed to create client socket");
                }
                std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";

                while (true) {
                    auto start_time = std::chrono::high_resolution_clock::now();

                    if (cli_sock.Send(req.c_str(), req.size()) == -1) {
                        throw std::runtime_error("Failed to send request");
                    }

                    char buf[1024] = {0};
                    if (!cli_sock.Recv(buf, 1023)) {
                        throw std::runtime_error("Failed to receive response");
                    }

                    auto end_time = std::chrono::high_resolution_clock::now();
                    std::chrono::duration<double> elapsed = end_time - start_time;

                    logMessage("Received: " + std::string(buf));
                    logMessage("Response time: " + std::to_string(elapsed.count()) + " seconds");
                }

                cli_sock.Close();
            } catch (const std::exception& e) {
                logMessage("Error: " + std::string(e.what()));
            }
            exit(0);
        }
    }

    signal(SIGINT, signalHandler); // 捕捉 SIGINT 信号，进行清理
    while (true) {
        sleep(1); // 主进程保持运行
    }

    return 0;
}
